//
//  WSTabBar.swift
//  WSWeiBo01
//
//  Created by 李维顺 on 16/7/10.
//  Copyright © 2016年 liweishun. All rights reserved.
//

import UIKit

//定义协议
protocol WSTabBarDelegate:NSObjectProtocol {
    func didSelectedButton()
}


class WSTabBar: UITabBar {
    
    //定义按钮的点击闭包
    var buttonClosure: (() -> ())?
    
    //定义代理
    weak var wsDelegate:WSTabBarDelegate?
    
    //懒加载按钮
    private lazy var button: UIButton = {
       let btn = UIButton()
        btn.addTarget(self, action: "clickButton", forControlEvents: UIControlEvents.TouchUpInside)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        //设置图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        btn.sizeToFit()
        return btn
        
        
    }()
    
    //点击事件
  @objc private func clickButton() {
//        print("哈哈")
        //调用闭包
        buttonClosure?()
        //代理方法
        wsDelegate?.didSelectedButton()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
       addSubview(button)
        
        
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        button.centerX = width * 0.5
        button.centerY = height * 0.5
        //获取系统空间
        //计算控件的宽度
        let itemWidth = width / 5
        var index = 0
        for value in subviews {
//            print(value)
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
//                print(value)
                value.x = itemWidth * CGFloat(index)
                value.width = itemWidth
                if index == 1 {
                    index++
                }
                index++
            }
        }
        
    }
    
    
    
    //加载xib和storyboard的时候才调用
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


















